import * as Blockly from 'blockly/core'

// 1.---------------字符串split分割成数组---------------------
const splitJson = {
  type: 'text_split',
  message0: '将文本 %1 用分隔符 %2 分割成字符串数组',
  args0: [
    // 动态生成选项
    {
      'type': 'input_value',
      'name': 'TEXT_INPUT',
      check: 'String'
    },
    {
      'type': 'field_input',
      'name': 'SEPERATOR',
      'text': ','
    }
  ],
  // previousStatement: true,
  // nextStatement: true,
  inputsInline: true,
  output: 'Array',
  colour: 160,
  tooltip: '该方法用于把一个字符串分割成字符串数组',
  helpUrl: ''
}
// 创建积木
Blockly.Blocks['text_split'] = {
  init: function () {
    this.jsonInit(splitJson)
  }
}

Blockly.JavaScript['text_split'] = function (block) {
  const text = Blockly.JavaScript.valueToCode(block, 'TEXT_INPUT',
    Blockly.JavaScript.ORDER_COMMA) || '[]'
  const seperator = Blockly.JavaScript.quote_(block.getFieldValue('SEPERATOR'))
  const code = `${text}.split(${seperator})`
  return [code, Blockly.JavaScript.ORDER_ATOMIC]
}

// 2------------join() 方法将数组作为字符串返回-----------------------
const joinJson = {
  type: 'array_join',
  message0: '将数组 %1 用分隔符 %2 转换成字符串',
  args0: [
    // 动态生成选项
    {
      'type': 'input_value',
      'name': 'ARRAY_INPUT',
      check: 'Array'
    },
    {
      'type': 'field_input',
      'name': 'SEPERATOR',
      'text': ','
    }
  ],
  // previousStatement: true,
  // nextStatement: true,
  inputsInline: true,
  output: 'String',
  colour: 230,
  tooltip: '该方法把数组中的所有元素转换一个字符串，元素是通过指定的分隔符进行分隔的，默认使用逗号作为分隔符',
  helpUrl: ''
}
// 创建积木
Blockly.Blocks['array_join'] = {
  init: function () {
    this.jsonInit(joinJson)
  }
}

Blockly.JavaScript['array_join'] = function (block) {
  const list = Blockly.JavaScript.valueToCode(block, 'ARRAY_INPUT',
    Blockly.JavaScript.ORDER_COMMA) || '[]'
  const seperator = Blockly.JavaScript.quote_(block.getFieldValue('SEPERATOR'))
  const code = `${list}.join(${seperator})`
  return [code, Blockly.JavaScript.ORDER_ATOMIC]
}
